package cn.ztq.test0614.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import cn.ztq.test0614.R;

public class SAct extends AppCompatActivity {
    ImageView blurredImageView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blur_activity);

        blurredImageView = findViewById(R.id.blurred_image_view);

        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_test);
        Bitmap blurredBitmap = blur(originalBitmap, getApplicationContext());

        blurredImageView.setImageBitmap(blurredBitmap);
    }

    public static Bitmap blur(Bitmap bitmap, Context context) {
        // 创建一个空的Bitmap用于输出
        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        // 初始化RenderScript
        RenderScript rs = RenderScript.create(context);

        // 创建一个intrinsic blur script
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

        // 分配内存输入和输出的图像
        Allocation input = Allocation.createFromBitmap(rs, bitmap);
        Allocation output = Allocation.createFromBitmap(rs, outBitmap);

        // 将输入图像传到内存中
        input.copyTo(output);

        // 设置模糊半径，值越高越模糊，一般范围1-25
        blurScript.setRadius(25f);

        // 运行脚本
        blurScript.setInput(output);
        blurScript.forEach(output);

        // 将输出的图像复制到outBitmap
        output.copyTo(outBitmap);

        // 释放内存
        input.destroy();
        output.destroy();
        blurScript.destroy();
        rs.destroy();

        return outBitmap;
    }
}
